// js/pages/LoginPage.js
import BasePage from './BasePage.js';
import TextRenderer from '../utils/TextRenderer.js';

// 提取常量
const UI_CONSTANTS = {
  BUTTON: {
    TEXT: '开 始',
    WIDTH: 224,
    HEIGHT: 80,
    Y: 552
  },
  TEXT: {
    HEALTH_WARNING_TITLE: '健康游戏忠告',
    HEALTH_WARNING_LINE1: '抵制不良游戏，拒绝盗版游戏。注意自我保护，谨防受骗上当。',
    HEALTH_WARNING_LINE2: '适度游戏益脑，沉迷游戏伤身。合理安排时间，享受健康生活。',
    COPYRIGHT: '著作权人：长沙财趣宝库信息科技合伙企业（有限合伙） 登记号：2018SR955664 版本号：1.0.0',
    FONT_SIZES: {
      TITLE: 44,
      WARNING: 36,
      BUTTON: 36,
      COPYRIGHT: 20
    }
  },
  COLORS: {
    BACKGROUND: '#ffffff',
    TEXT: '#161109'
  },
  POSITIONS: {
    LOGO: { Y: 108, WIDTH: 450, HEIGHT: 164 },
    WARNING_TITLE: { Y: 292 },
    WARNING_LINE1: { Y: 378 },
    WARNING_LINE2: { Y: 448 },
    BUTTON_TEXT: { Y: 578 },
    COPYRIGHT: { Y: 708 }
  }
};

export default class LoginPage extends BasePage {
  constructor(canvas, ctx, pageManager, resourceManager, screenAdapter, api, userManager) {
    super(canvas, ctx, pageManager, resourceManager, screenAdapter);
    this.isLoggingIn = false;
    this.api = api;
    this.textRenderer = new TextRenderer(ctx, screenAdapter);
    this.button = null;
    this.isInitialized = false;
  }

  async onInit() {
    return Promise.resolve();
  }

  /**
   * 页面初始化方法
   */
  async initialize() {
    try {
      await this.initializeUI();
      await this.fetchGameData();
      this.isInitialized = true;
    } catch (error) {
      console.error('页面初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化UI元素
   */
  async initializeUI() {
    const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
    
    this.button = {
      text: UI_CONSTANTS.BUTTON.TEXT,
      x: centerX - UI_CONSTANTS.BUTTON.WIDTH / 2,
      y: UI_CONSTANTS.BUTTON.Y,
      width: UI_CONSTANTS.BUTTON.WIDTH,
      height: UI_CONSTANTS.BUTTON.HEIGHT,
      action: () => this.handleLogin()
    };
  }

  /**
   * 获取游戏数据
   */
  async fetchGameData() {
    // 预留获取游戏数据的逻辑
  }

  /**
   * 渲染页面
   */
  render() {
    if (!this.isInitialized) return;

    this.renderBackground();
    this.renderLogo();
    this.renderHealthWarning();
    this.renderCopyright();
    this.renderButton();
  }

  /**
   * 渲染背景
   */
  renderBackground() {
    this.ctx.fillStyle = UI_CONSTANTS.COLORS.BACKGROUND;
    this.ctx.fillRect(0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);
  }

  /**
   * 渲染Logo
   */
  renderLogo() {
    const loadingLog = this.resourceManager.getImage('loadingLog');
    if (loadingLog) {
      const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
      this.ctx.drawImage(
        loadingLog,
        centerX - UI_CONSTANTS.POSITIONS.LOGO.WIDTH / 2,
        UI_CONSTANTS.POSITIONS.LOGO.Y,
        UI_CONSTANTS.POSITIONS.LOGO.WIDTH,
        UI_CONSTANTS.POSITIONS.LOGO.HEIGHT
      );
    }
  }

  /**
   * 渲染健康游戏忠告
   */
  renderHealthWarning() {
    const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
    const { TEXT, POSITIONS } = UI_CONSTANTS;

    // 标题
    this.textRenderer.drawText(
      TEXT.HEALTH_WARNING_TITLE,
      centerX,
      POSITIONS.WARNING_TITLE.Y,
      `bold ${UI_CONSTANTS.TEXT.FONT_SIZES.TITLE}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT,
      'center',
      'top'
    );

    // 警告内容
    this.textRenderer.drawText(
      TEXT.HEALTH_WARNING_LINE1,
      centerX,
      POSITIONS.WARNING_LINE1.Y,
      `${UI_CONSTANTS.TEXT.FONT_SIZES.WARNING}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT,
      'center',
      'top'
    );

    this.textRenderer.drawText(
      TEXT.HEALTH_WARNING_LINE2,
      centerX,
      POSITIONS.WARNING_LINE2.Y,
      `${UI_CONSTANTS.TEXT.FONT_SIZES.WARNING}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT,
      'center',
      'top'
    );
  }

  /**
   * 渲染版权信息
   */
  renderCopyright() {
    const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
    
    this.textRenderer.drawText(
      UI_CONSTANTS.TEXT.COPYRIGHT,
      centerX,
      UI_CONSTANTS.POSITIONS.COPYRIGHT.Y,
      `${UI_CONSTANTS.TEXT.FONT_SIZES.COPYRIGHT}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT,
      'center',
      'top'
    );
  }

  /**
   * 渲染按钮
   */
  renderButton() {
    const loadingBtn = this.resourceManager.getImage('loadingBtn');
    if (loadingBtn) {
      this.ctx.drawImage(
        loadingBtn,
        this.button.x,
        this.button.y,
        this.button.width,
        this.button.height
      );
    }

    // 按钮文字
    this.textRenderer.drawText(
      this.button.text,
      this.screenAdapter.DESIGN_WIDTH / 2,
      UI_CONSTANTS.POSITIONS.BUTTON_TEXT.Y,
      `${UI_CONSTANTS.TEXT.FONT_SIZES.BUTTON}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT,
      'center',
      'top'
    );
  }

  /**
   * 处理触摸开始事件
   */
  handleTouchStart(event) {
    // 可以在这里添加按钮按下效果
  }

  /**
   * 处理触摸结束事件
   */
  handleTouchEnd(event) {
    if (this.isLoggingIn) return;

    const touch = event.changedTouches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    if (this.isButtonClicked(logicPoint)) {
      this.handleLogin();
    }
  }

  /**
   * 处理触摸移动事件
   */
  handleTouchMove(event) {
    // 预留触摸移动处理逻辑
  }

  /**
   * 检查按钮是否被点击
   */
  isButtonClicked(point) {
    return point.x >= this.button.x &&
           point.x <= this.button.x + this.button.width &&
           point.y >= this.button.y &&
           point.y <= this.button.y + this.button.height;
  }

  /**
   * 处理登录逻辑
   */
  async handleLogin() {
    if (this.isLoggingIn) return;

    this.isLoggingIn = true;
    
    try {
      const userProfile = await this.api.user.getUserProfile();
      
      if (userProfile.data.ID === 0) {
        await this.createNewUser();
      } else {
        await this.handleLoginSuccess(userProfile.data);
      }
    } catch (error) {
      console.error('登录过程中发生错误:', error);
      // 可以在这里添加错误提示
    } finally {
      this.isLoggingIn = false;
    }
  }

  /**
   * 创建新用户
   */
  async createNewUser() {
    const randomNumber = Math.floor(Math.random() * 90) + 10;
    const userName = `用户${randomNumber}`;
    
    try {
      await this.api.user.add({
        user_name: userName,
        avatar: 'https://www.zmkxds.cn/images/defaultAvatar.png'
      });
      
      // 创建成功后重新获取用户信息
      await this.handleLogin();
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }

  /**
   * 处理登录成功
   */
  async handleLoginSuccess(userData) {
    try {
      // 存储用户数据（根据实际平台调整存储方式）
      if (typeof wx !== 'undefined') {
        wx.setStorageSync('userData', userData);
        wx.setStorageSync('userBalance', userData.balance);
      }
      
      // 跳转到主页
      this.pageManager.showPage('home');
    } catch (error) {
      console.error('处理登录成功逻辑失败:', error);
      throw error;
    }
  }
}
